package linter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import linter.POJO.DO.ClassData;
import linter.POJO.DO.UserClass;
import linter.POJO.DO.UserClassPlan;
import linter.mapper.ClassDataMapper;
import linter.mapper.UserClassMapper;
import linter.mapper.UserClassPlanMapper;
import linter.service.UserClassService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static linter.custom.CustomResultType.SAVE_NOT_ERROR;
import static linter.custom.CustomResultType.SAVE_SUCCESS;

/**
* @author 北煜
* @description 针对表【user_class(用户课程关系表)】的数据库操作Service实现
* @createDate 2024-04-10 11:26:36
*/
@Service
public class UserClassServiceImpl extends ServiceImpl<UserClassMapper, UserClass>
    implements UserClassService{
    @Resource
    UserClassMapper userClassMapper;
    @Resource
    ClassDataMapper classDataMapper;
    @Resource
    UserClassPlanMapper userClassPlanMapper;

    @Override
    public Double getClassPlan(String classType, Long uuid) {
        QueryWrapper<UserClass> queryWrapperUserClass = new QueryWrapper<>();
        QueryWrapper<ClassData> queryWrapper = new QueryWrapper<>();
        Long userClassCount = classDataMapper.selectCount(queryWrapper.eq("class_type", classType));
        List<UserClass> listUserClass = userClassMapper.selectList(queryWrapperUserClass.eq("uuid", uuid).
                eq("class_type",classType));
        List<Integer> classIsFinish = listUserClass.stream().map(UserClass::getIsFinish).collect(Collectors.toList());
        double finishCount = classIsFinish.stream().map(i -> i == 1 ? 0.5 : (i == 2 ? 1 : i)).mapToDouble(Double::valueOf).sum();
        double result = userClassCount / 100 * finishCount;
        // 将用户的课程进度进行保存
        Date date = new Date();
        UserClassPlan userClassPlan = new UserClassPlan();
        userClassPlan.setUuid(uuid);
        userClassPlan.setClassType(classType);
        userClassPlan.setClassPlan(result);
        userClassPlan.setUpdateTime(date);
        int flag = userClassPlanMapper.insert(userClassPlan);
        if (flag != 1) { System.out.println(SAVE_NOT_ERROR); }
        return result;
    }

    @Override
    public String classNodeIsFinish(String classType, Integer classId, Integer classNode, Integer isFinish, Long uuid) {
        UserClass userClass = new UserClass();
        userClass.setClassId(classId);
        userClass.setClassNode(classNode);
        userClass.setIsFinish(isFinish);
        userClass.setUuid(uuid);
        userClass.setClassType(classType);
        int flag = userClassMapper.insert(userClass);
        return flag != 1 ? SAVE_NOT_ERROR : SAVE_SUCCESS;
    }
}




